package com.fh.qqserver.service;

import com.fh.qqcommon.Message;
import com.fh.qqcommon.MessageType;
import com.fh.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author 方小勤
 * @version 1.0~
 * 发送新闻
 */
public class SendNewsToAllService implements Runnable {
    @Override
    public void run() {
        while(true) {
            System.out.println("请输入服务器要推送的新闻/消息[输入exit表示退出推送服务]");
            String news = Utility.readString(100);
            if(news.equals("exit")) {
                break;
            }
            //构建一个消息，群发消息
            Message message = new Message();
            message.setSender("服务器");
            message.setMesType(MessageType.MESSAGE_TO_ALL_FRIEND);
            message.setContent(news);
            message.setTime(new Date().toString());
            System.out.println("服务器推送消息给所有人 说： " + news);
            //遍历当前所有的通讯线程，得到socket，并发送message
            HashMap<String, ServerConnectClientThread> serverConnectClientThreadHashMap = ManageClientThreads.getServerConnectClientThreadHashMap();
            Iterator<String> iterator = serverConnectClientThreadHashMap.keySet().iterator();
            while (iterator.hasNext()) {
                String onlineId = iterator.next().toString();
                ServerConnectClientThread serverConnectClientThread = serverConnectClientThreadHashMap.get(onlineId);
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(serverConnectClientThreadHashMap.get(onlineId).getSocket().getOutputStream());
                    objectOutputStream.writeObject(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
